<?php
namespace App\Models;

use App\Utils\Sms;
use Exception;
use Mail;
use Request;

/**
 * 日志类
 */
class MSmsCode extends BaseModel
{
    public $table = "sms_code";

    public static $TYPE_TEL = 0;    //短信验证码标识
    public static $TYPE_EMAIL = 1;  //邮箱验证码标识

    /**
     * 记录一条短信记录
     */
    public static function log($contact_info, $code, $close_time, $flag)
    {
        $log = new MSmsCode();
        if ($flag == self::$TYPE_TEL) {
            $log->mobile = $contact_info;
        } elseif ($flag == self::$TYPE_EMAIL) {
            $log->email = $contact_info;
        }
        $log->sms_code = $code;
        $log->sms_close_time = $close_time;
        return $log->save();
    }

    /**
     * 发送验证码   调用
     * @param $type 模板类型
     * @param $tel  手机号
     * @param null $name 用户名
     * @return bool|int
     */
    public static function send_yzm($type, $tel, $name = null)
    {
        $codeLog = MSmsCode::where('mobile', $tel)->where('sms_is_used', 0)->orderBy('id', 'desc')->first();

        if (empty($codeLog)) {  //发送短信
            return self::send_sms_code($type, $tel, $name);
        }

        //如果验证码已经发送，并且还在有效期内，则不在发送短信
        if (strtotime($codeLog->sms_close_time) > time()) {
            $second = strtotime($codeLog->sms_close_time) - time();
            return $second;
        } else {
            //验证码过期
            if (self::changeUsed($codeLog) && self::send_sms_code($type, $tel, $name)) {
                return true;
            } else {
                return false;
            }
        }

    }

    /**
     * 发送邮件验证码 调用
     * @param $email
     * @return bool|int
     */
    public static function send_email_code($email)
    {
        $codeLog = MSmsCode::where('email', $email)->where('sms_is_used', 0)->orderBy('id', 'desc')->first();

        if (empty($codeLog)) {  //发送短信
            return self::send_email($email);
        } else {
            //如果验证码已经发送，并且还在有效期内，则不在发送短信
            if (strtotime($codeLog->sms_close_time) > time()) {
                $second = strtotime($codeLog->sms_close_time) - time();
                return $second;
            } else {
                //验证码过期
                if (self::changeUsed($codeLog) && self::send_email($email)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 发送验证码并生成记录
     */
    public static function send_sms_code($type, $tel, $name = null)
    {
        //发送短信
        $str = "0123456789";
        //截取6位数字的验证码
        $new_str = substr(str_shuffle($str), 0, 6);
        if (empty($name)) {
            $arr['code'] = $new_str;
        } else {
            $arr['username'] = $name;
            $arr['valicode'] = $new_str;
        }

        //发送短信
        Sms::send($type, $tel, $arr);

        //生成短信记录
        return self::log($tel, $new_str, date("Y-m-d H:i:s", strtotime("+2 minute")), self::$TYPE_TEL);
    }

    /**
     * @param $email
     * @return bool
     */
    public static function send_email($email)
    {
        $str = "0123456789";
        //截取6位数字的验证码
        $new_str = substr(str_shuffle($str), 0, 6);
        try {
            Mail::send('system.coms.findpass-template', ['code' => $new_str], function ($m) use ($email) {
                $m->subject("密码找回邮件，请查收！")
                    ->from(cv("email.username", env("MAIL_USERNAME"), true), cv('website.site_name'))
                    ->to($email);
            });
            return self::log($email, $new_str, date("Y-m-d H:i:s", strtotime("+5 minute")), self::$TYPE_EMAIL);
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * @param $contact_info 手机号或邮箱
     * @param $code 验证码
     * @param $flag 标识
     * @return bool|int int过期 true正确
     */
    public static function check_code($contact_info, $code, $flag)
    {
        if ($flag == self::$TYPE_TEL) {
            $log = MSmsCode::where('mobile', $contact_info)->where('sms_code', $code)->where('sms_is_used', 0)->first();
        } elseif ($flag == self::$TYPE_EMAIL) {
            $log = MSmsCode::where('email', $contact_info)->where('sms_code', $code)->where('sms_is_used', 0)->first();
        }

        if (empty($log)) {
            return false;
        }
        if (strtotime($log->sms_close_time) < time()) { //已过期
            $second = time() - strtotime($log->sms_close_time);
            return $second;
        }

        if (MSmsCode::changeUsed($log)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 修改短信记录状态为已使用
     * @param $log  短信记录
     * @return mixed
     */
    public static function changeUsed($log)
    {
        $log->sms_is_used = 1;
        return $log->save();
    }
}